package chap_01_CompletableFuture.step_03_interrupt;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @Description 借助AtomicBoolean，来实现线程的中断、停止
 * @Author shihan
 * @Date 2022/10/22 15:45
 * @Version 1.0
 */
public class InterruptDemo_02_AutomaticBoolean {

    /**
     * TODO：为什么 AutomaticBoolean 能像 volatile 修饰的变量一样，在多线程之间实现共享？
     */
    static AtomicBoolean isStop = new AtomicBoolean(false);

    public static void main(String[] args) {
        new Thread(() -> {
            // 需要不断地 while 循环去判断 AtomicBoolean 变量的值，增加消耗
            while (true) {
                if (isStop.get()) {
                    System.out.println(Thread.currentThread().getName() + "线程识别到AtomicBoolean变量的修改，终止！");
                    break;
                }
                System.out.println(Thread.currentThread().getName() + "正在运行...");
            }
        }, "t1").start();

        new Thread(() -> {
            isStop.set(true);
            System.out.println(Thread.currentThread().getName() + "对AtomicBoolean变量进行修改！");
        }, "t2").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("主线程结束！");
    }

}
